import axios from 'axios';
// import { MessageBox, Message } from "element-ui";
import { apiJava, env, n_d_version } from '@/api/root';
import { router } from '@/router';
import { showToast } from 'vant';

// 获取当前的路由对象

const service = axios.create({
  baseURL: apiJava, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // 增加到30秒
  retry: 3, // 重试次数
  retryDelay: 1000, // 重试间隔
});

// 创建一个请求队列，用于存储需要重试的请求
const pendingRequests = [];

// 添加token刷新状态管理
const tokenRefreshState = {
  isRefreshing: false,
  refreshPromise: null,
  refreshTimeout: null,
};

// 优化token刷新处理函数
const handleTokenRefresh = () => {
  // 如果已经在刷新中，直接返回当前的刷新Promise
  if (tokenRefreshState.isRefreshing) {
    return tokenRefreshState.refreshPromise;
  }

  tokenRefreshState.isRefreshing = true;

  // 创建一个新的Promise来处理token刷新
  tokenRefreshState.refreshPromise = new Promise((resolve, reject) => {
    if (!window.AndroidJs) {
      tokenRefreshState.isRefreshing = false;
      tokenRefreshState.refreshPromise = null;
      reject(new Error('非安卓环境'));
      return;
    }

    // 设置超时处理
    tokenRefreshState.refreshTimeout = setTimeout(() => {
      tokenRefreshState.isRefreshing = false;
      tokenRefreshState.refreshPromise = null;
      reject(new Error('获取token超时'));
    }, 10000); // 10秒超时

    // 创建一次性事件监听器
    const tokenUpdateHandler = (event) => {
      try {
        if (event.data && event.data.token) {
          // 清除超时定时器
          clearTimeout(tokenRefreshState.refreshTimeout);

          // 更新token
          localStorage.setItem('token', event.data.token);

          // 移除事件监听器
          window.removeEventListener('message', tokenUpdateHandler);

          // 重置状态
          tokenRefreshState.isRefreshing = false;
          tokenRefreshState.refreshPromise = null;

          resolve(event.data.token);
        }
      } catch (error) {
        // 处理token更新失败
        clearTimeout(tokenRefreshState.refreshTimeout);
        window.removeEventListener('message', tokenUpdateHandler);
        tokenRefreshState.isRefreshing = false;
        tokenRefreshState.refreshPromise = null;
        reject(error);
      }
    };

    // 添加事件监听器
    window.addEventListener('message', tokenUpdateHandler);

    // 请求新token
    const params = {
      action: 'getToken',
      extra: '',
    };
    window.AndroidJs.h5MessageToAndroid(JSON.stringify(params));
  });

  return tokenRefreshState.refreshPromise;
};

// 请求重试机制
service.interceptors.response.use(null, async (error) => {
  const config = error.config;

  // 如果没有设置重试配置，或者已经重试完成，则直接返回错误
  if (!config || !config.retry || config.retryCount >= config.retry) {
    return Promise.reject(error);
  }

  // 设置重试次数
  config.retryCount = config.retryCount || 0;
  config.retryCount++;

  // 延迟重试
  await new Promise((resolve) => setTimeout(resolve, config.retryDelay));

  // 重新发起请求
  return service(config);
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加网络状态检测
    if (!navigator.onLine) {
      showToast('网络连接已断开，请检查网络设置');
      return Promise.reject(new Error('网络连接已断开'));
    }

    if (config.data) {
      config.headers['id'] =
        config.data.ylPositionId ||
        config.data.positionId ||
        config.data.id ||
        0;
    } else if (config.params) {
      config.headers['id'] =
        config.params.ylPositionId ||
        config.params.positionId ||
        config.params.id ||
        0;
    } else {
      config.headers['id'] = 0;
    }

    if (env == 'local') {
      config.headers[
        'n-d-version'
      ] = `{"yl1001-boot-career-report":"${n_d_version}","yl1001-boot-occupation-platform":"${n_d_version}","yl1001-boot-subject-database":"${n_d_version}","yl1001-boot-file":"${n_d_version}"}`; // 使用变量
    }
    let token = '';
    let SecretKey = '';
    if (localStorage.getItem('token')) {
      token = localStorage.getItem('token');
    } else if (localStorage.getItem('userInfo')) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      token = userInfo.token;
    }
    if (localStorage.getItem('SecretKey')) {
      SecretKey = localStorage.getItem('SecretKey');
    }

    config.headers['Authorization'] = token || '';
    // config.headers['Authorization'] =
    //   'Bearer 28a7d23e-f80f-4a32-9018-d14403f59b7c';
    // TODO:SecretKey目前是写死的，后续需要改成再说
    config.headers['SecretKey'] =
      SecretKey || '6c95e857588f5e3381d68e7bdfb9ad9b';
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 优化响应拦截器中的token刷新处理
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    let res = response.data;
    if (res.code != null && res.code == 401) {
      const config = response.config;

      // 将当前请求添加到队列
      if (!pendingRequests.includes(config)) {
        pendingRequests.push(config);
      }

      // 处理token刷新
      return handleTokenRefresh()
        .then((newToken) => {
          if (newToken) {
            // 更新所有待处理请求的token
            pendingRequests.forEach((requestConfig) => {
              requestConfig.headers['Authorization'] = newToken;
            });

            // 重试所有请求
            return Promise.all(
              pendingRequests.map((requestConfig) => service(requestConfig))
            ).then((results) => {
              // 清空请求队列
              pendingRequests.length = 0;
              // 返回当前请求的结果
              return results[0];
            });
          }
          return Promise.reject(new Error('未授权'));
        })
        .catch((error) => {
          // 处理token刷新失败
          showToast('网络异常1，请稍后重试');
          // 清空请求队列
          pendingRequests.length = 0;
          return Promise.reject(error);
        });
    }
    return res;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      const config = error.config;

      // 将当前请求添加到队列
      if (!pendingRequests.includes(config)) {
        pendingRequests.push(config);
      }

      // 处理token刷新
      return handleTokenRefresh()
        .then((newToken) => {
          if (newToken) {
            // 更新所有待处理请求的token
            pendingRequests.forEach((requestConfig) => {
              requestConfig.headers['Authorization'] = newToken;
            });

            // 重试所有请求
            return Promise.all(
              pendingRequests.map((requestConfig) => service(requestConfig))
            ).then((results) => {
              // 清空请求队列
              pendingRequests.length = 0;
              // 返回当前请求的结果
              return results[0];
            });
          }
          return Promise.reject(error);
        })
        .catch((error) => {
          // 处理token刷新失败
          showToast('网络异常2，请稍后重试');
          // 清空请求队列
          pendingRequests.length = 0;
          return Promise.reject(error);
        });
    }

    // 处理其他错误
    if (error.code === 'ECONNABORTED') {
      showToast('请求超时，请稍后重试');
    } else if (!navigator.onLine) {
      showToast('网络连接已断开，请检查网络设置');
    } else if (error.response) {
      switch (error.response.status) {
        case 403:
          showToast('没有权限访问');
          break;
        case 404:
          showToast('请求的资源不存在');
          break;
        case 500:
          showToast('服务器错误');
          break;
        default:
          showToast('网络错误，请稍后重试');
      }
    } else {
      showToast('网络错误，请稍后重试');
    }
    return Promise.reject(error);
  }
);

export default service;
